
#include <fstream>
#include <string>
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "date_time.h"
#include "gpb_util.h"
#include "gps.pb.h"
#include "gpx_parser.h"
#include "kml_segments.h"
#include "kml/base/math_util.h"

DEFINE_string(ingpx, "", "file.gpx");
DEFINE_string(outkml, "", "file.kml");
DEFINE_int32(min_points, 10, "mininum points per segment");

int main(int argc, char** argv) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);
  //FLAGS_logtostderr = true;
  if (FLAGS_ingpx.empty()) {
    LOG(ERROR) << "missing arg --ingpx file.gpx";
    return 1;
  }
  
  gps_proto::GpsProto gps_proto;
  if (!gps_proto::GpxParser::ParseFromFile(FLAGS_ingpx.c_str(), &gps_proto)) {
    LOG(ERROR) << "parse failed: " << FLAGS_ingpx;
    return 1;
  }

#if 0
  //std::cout << "<track> size " << gps_proto.track_size() << std::endl;
  for (int t = 0; t < gps_proto.track_size(); ++t) {
    //std::cout << "<segment> size " << gps_proto.track(t).segment_size() << std::endl;
    for (int s = 0; s < gps_proto.track(t).segment_size(); ++s) {
      const gps_proto::SegmentProto& segment = gps_proto.track(t).segment(s);
      int num_points = segment.point_size();
      if (num_points > FLAGS_min_points) {
        std::cout << "start "
                  << gps_proto::DateTime::ToDateTime(segment.point(0).time())
                  << ", "
                  << segment.point(num_points-1).time() -
                     segment.point(0).time()
                  << " seconds, "
                  << num_points
                  << " points " << std::endl;
      }
    }
  }
#endif
  if (!FLAGS_outkml.empty()) {
    kmldom::KmlFactory* kml_factory(kmldom::KmlFactory::GetFactory());
    kmldom::KmlPtr kml = kml_factory->CreateKml();
    kml->set_feature(gps_proto::KmlSegments::CreateDocument(gps_proto));
    std::cout << kmldom::SerializePretty(kml);
  }
  return 0;
}

